<?php
namespace app\index\controller;
use think\Db;
use jwt\Jwt;
class Order extends Common{
    
    /**
     * 微信支付回调
     * @return [type] [description]
     */
    function weixinpay(){
        $xml = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : '';
        if(empty($xml)){
            return 'fail';
        }
        $e = xmlToArray($xml);
        if(empty($e)){
            return 'fail';
        }
        // model('aa_log')->add([
        //     'msg'=>json_encode($e),
        //     's_date'=>date('Y-m-d H:i')
        // ]);
        if($e['result_code']!=='SUCCESS'){
            return $e['err_code_des'];
        }
        $sign = \weixinpay\Weixinpay::sign($e,config('config.weixinpay_key')); 
        if($sign!==$e['sign']){
           return 'fail';
        }
        $order_number=$e['out_trade_no']; //平台订单号
        $trade_no=$e['transaction_id']; //微信订单号
        $cash_fee=$e['cash_fee']/100; //用户支付金额
        $rs=model('order')->orderHandle($order_number,$trade_no,$cash_fee);
        if(true!==$rs){
            logger('error',lang('user order fail',[
                '微信',
                $order_number,
                $trade_no,
                $cash_fee,
                $rs,
            ]));
            return $rs;
        }
        return arrayToXml([
            'return_code'=>'SUCCESS',
            'return_msg'=>'OK',
        ]);
    }
    /**
     * 支付宝支付回调
     * @return [type] [description]
     */
    function alipay(){
        // 支付宝交易号:trade_no  商户订单号:out_trade_no
        $e=input('post.');
        // model('aa_log')->add([
        //     'msg'=>json_encode($e),
        //     's_date'=>date('Y-m-d H:i')
        // ]);
        if(isset($e['trade_status'])&&$e['trade_status']==='TRADE_SUCCESS'){
            $c = alipayClient();
            //此处验签方式必须与下单时的签名方式一致
            $flag = $c->rsaCheckV1($e, null, $e['sign_type']);
            
            if(!$flag){
                return json('订单验证失败',1);
            }
            $order_number=$e['out_trade_no']; //平台订单号
            $trade_no=$e['trade_no']; //支付宝单号
            $cash_fee=$e['buyer_pay_amount']; //用户支付金额

            $rs=model('order')->orderHandle($order_number,$trade_no,$cash_fee);
            if(true!==$rs){
                logger('error',lang('user order fail',[
                    '支付宝',
                    $order_number,
                    $trade_no,
                    $cash_fee,
                    $rs,
                ]));
                return $rs;
            }
            return 'success';
        }
    }
    
}